// fast模态框
(function(window) {
    class Fast {
        constructor() {
            this.zIndex = 1000;
            this.instances = new Map();
            // 初始化表单功能
            this.form = new FastForm();
            
            // 定义版本信息
            this._version = '1.0.0';
            this.author = 'AdilJan';
            this.email = '1394025288@qq.com';
            this.website = 'orhun.cn';

            // 设置 version 的 getter
            Object.defineProperty(this, 'version', {
                get: function() {
                    this._showInfo();
                    return this._version;
                }
            });
        }

        // 添加显示信息的方法
        _showInfo() {
            const styles = {
                logo: [
                    'font-size: 20px',
                    'font-weight: bold',
                    'color: #2d8cf0',
                    'font-family: monospace',
                    'line-height: 1.4'
                ].join(';'),
                info: [
                    'color: #666',
                    'font-size: 14px',
                    'font-family: monospace',
                    'line-height: 1.5'
                ].join(';')
            };

            console.log(`%c
    ███████╗ █████╗ ███████╗████████╗██╗      █████╗ ██╗   ██╗███████╗██████╗ 
    ██╔════╝██╔══██╗██╔════╝╚══██╔══╝██║     ██╔══██╗╚██╗ ██╔╝██╔════╝██╔══██╗
    █████╗  ███████║███████╗   ██║   ██║     ███████║ ╚████╔╝ █████╗  ██████╔╝
    ██╔══╝  ██╔══██║╚════██║   ██║   ██║     ██╔══██║  ╚██╔╝  ██╔══╝  ██╔══██╗
    ██║     ██║  ██║███████║   ██║   ███████╗██║  ██║   ██║   ███████╗██║  ██║
    ╚═╝     ╚═╝  ╚═╝╚══════╝   ╚═╝   ╚══════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝
`, styles.logo);

            console.log(`%c
╔════════════════════════════════════════════════════════════�
║                                                            ║
║   Version: ${this._version.padEnd(45, ' ')}║
║   Author:  ${this.author.padEnd(45, ' ')}║
║   Email:   ${this.email.padEnd(45, ' ')}║
║   Website: ${this.website.padEnd(45, ' ')}║
║                                                            ║
╚════════════════════════════════════════════════════════════╝
`, styles.info);
        }

        // 基础配置
        config = {
            type: 0,
            title: '信息',
            content: '',
            area: 'auto',
            offset: 'auto',
            icon: -1,
            btn: ['确定', '取消'],
            btnAlign: 'r',
            closeBtn: 1,
            shade: 0.3,
            shadeClose: false,
            time: 0,
            anim: 0,
            isOutAnim: true,
            maxmin: false,
            fixed: true,
            resize: false,
            scrollbar: true,
            maxWidth: 360,
            maxHeight: 400,
            zIndex: 19891014,
            move: '.fast-layer-title',
            moveOut: false,
            drag: false,
            skin: '',
        }

        alert(content, options = {}, yes = null) {
            // 如果有图标，添加图标HTML
            if (options.icon !== undefined) {
                content = this._getIconHtml(options.icon) + content;
            }

            return this.open({
                ...this.config,
                type: 0,
                content: content,
                ...options
            }, yes);
        }

        confirm(content, options = {}, yes = null, cancel = null) {
            options.content = content;
            options.type = 0;
            return this.open({...this.config, ...options}, yes, cancel);
        }

        msg(content, options = {}, end = null) {
            // 如果第二个参数是函数，则视为回调
            if (typeof options === 'function') {
                end = options;
                options = {};
            }

            let config = {
                content: content,
                time: options.time ?? 3000,
                shade: options.shade ?? false,
                skin: options.skin,
                btn: options.btn,
                yes: options.yes
            };

            // 处理图标
            if (options.icon !== undefined) {
                config.content = this._getIconHtml(options.icon) + config.content;
            }

            // 创建或获取消息容器
            let container = document.querySelector('.fast-msg-container');
            if (!container) {
                container = document.createElement('div');
                container.className = 'fast-msg-container';
                document.body.appendChild(container);
            }

            // 创建消息元素
            const msgElem = document.createElement('div');
            const rtlClass = this._isRTL() ? 'fast-layer-rtl' : '';
            msgElem.className = `fast-layer fast-msg ${rtlClass} ${config.skin || ''}`;
            
            // 如果是 RTL 模式，调整图标和文本的顺序
            if (this._isRTL()) {
                msgElem.innerHTML = `<div class="fast-layer-content">${config.content}</div>`;
            } else {
                msgElem.innerHTML = `<div class="fast-layer-content">${config.content}</div>`;
            }

            // 添加到容器
            container.appendChild(msgElem);

            // 如果需要抖动效果
            if (options.shake) {
                // 等待元素渲染完成后添加抖动效果
                setTimeout(() => {
                    msgElem.classList.add('shake');
                    // 动画结束后移除类名，以便支持多次抖动
                    msgElem.addEventListener('animationend', () => {
                        msgElem.classList.remove('shake');
                    });
                }, 0);
            }

            // 自动关闭
            if (config.time > 0) {
                setTimeout(() => {
                    msgElem.classList.add('closing');
                    
                    setTimeout(() => {
                        msgElem.remove();
                        if (end) end();
                        
                        // 如果容器为空，也移除容器
                        if (container.children.length === 0) {
                            container.remove();
                        }
                    }, 300);
                }, config.time);
            }

            return msgElem;
        }

        load(icon = 0, options = {}) {
            let loadingHtml = `<div class="fast-loading-container">`;
            
            // 根据不同类型生成不同的loading HTML
            switch(icon) {
                case 4:
                    loadingHtml += `
                        <div class="fast-loading fast-loading-4">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    `;
                    break;
                case 6:
                    loadingHtml += `
                        <div class="fast-loading fast-loading-6">
                            <span></span>
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    `;
                    break;
                default:
                    loadingHtml += `<div class="fast-loading fast-loading-${icon}"></div>`;
            }
            
            // 添加文字
            if (options.text) {
                loadingHtml += `<div class="fast-loading-text">${options.text}</div>`;
            }
            
            loadingHtml += '</div>';

            return this.open({
                ...this.config,
                type: 3,
                content: loadingHtml,
                shade: options.shade ?? 0.01,
                closeBtn: 0,
                time: options.time || 0,
                skin: 'fast-loading-layer',
                area: 'auto',
                offset: 'auto'
            });
        }

        tips(content, follow, options = {}) {
            return this.open({
                ...this.config,
                type: 4,
                content: [content, follow],
                closeBtn: false,
                time: 3000,
                shade: false,
                maxWidth: 210,
                ...options
            });
        }

        open(options = {}, yes = null, cancel = null) {
            const config = {...this.config, ...options};
            const id = this._createId();
            
            // 创建DOM
            const elem = this._createElem(config, id);
            document.body.appendChild(elem);
            
            // 绑定事件
            this._bindEvents(elem, config, id, yes, cancel);
            
            // 动画
            this._anim(elem, config.anim);
            
            return id;
        }

        close(id) {
            const elem = document.querySelector(`#${id}`);
            if (elem) {
                this.instances.delete(id);
                elem.remove();
            }
        }

        // 私有方法（使用下划线前缀）
        _createId() {
            return 'fast-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
        }

        _createElem(config, id) {
            const wrapper = document.createElement('div');
            wrapper.id = id;
            
            const rtlClass = this._isRTL() ? 'fast-layer-rtl' : '';
            wrapper.className = `fast-layer ${rtlClass} ${config.skin || ''}`;
            wrapper.style.zIndex = this.zIndex++;

            let html = '';
            
            if (config.shade) {
                html += `<div class="fast-layer-shade" style="opacity:${config.shade}"></div>`;
            }

            if (config.type === 3) {
                html += config.content;
            } else {
                html += '<div class="fast-layer-main">';
                
                // 修改标题栏，添加最大化/最小化按钮
                if (config.title !== false) {
                    html += `
                        <div class="fast-layer-title">
                            <span class="fast-layer-title-text">${config.title}</span>
                            ${config.maxmin ? `
                                <div class="fast-layer-title-btns">
                                    <button type="button" class="fast-layer-min" title="最小化"></button>
                                    <button type="button" class="fast-layer-max" title="最大化"></button>
                                </div>
                            ` : ''}
                        </div>
                    `;
                }

                html += `<div class="fast-layer-content">${config.content}</div>`;

                if (config.btn) {
                    html += '<div class="fast-layer-btn">';
                    config.btn.forEach((btn, index) => {
                        html += `<button type="button" class="fast-btn ${index === 0 ? 'fast-btn-primary' : ''}">${btn}</button>`;
                    });
                    html += '</div>';
                }

                if (config.closeBtn) {
                    html += '<button type="button" class="fast-layer-close"></button>';
                }

                // 添加调整大小的手柄
                if (config.resize) {
                    html += '<div class="fast-layer-resize"></div>';
                }

                html += '</div>';
            }
            
            wrapper.innerHTML = html;
            return wrapper;
        }

        _bindEvents(elem, config, id, yes, cancel) {
            // 关闭按钮事件
            const closeBtn = elem.querySelector('.fast-layer-close');
            if (closeBtn) {
                closeBtn.onclick = () => this.close(id);
            }

            // 遮罩层关闭
            if (config.shadeClose) {
                const shade = elem.querySelector('.fast-layer-shade');
                if (shade) {
                    shade.onclick = () => this.close(id);
                }
            }

            // 按钮事件
            const btns = elem.querySelectorAll('.fast-layer-btn .fast-btn');
            if (btns.length > 0) {
                btns[0].onclick = () => {
                    if (yes) yes();
                    this.close(id);
                };
                if (btns[1] && cancel) {
                    btns[1].onclick = () => {
                        cancel();
                        this.close(id);
                    };
                }
            }

            // 添加拖拽功能
            if (config.move && config.drag) {
                const moveElem = elem.querySelector(config.move);
                const mainElem = elem.querySelector('.fast-layer-main');
                
                if (moveElem && mainElem) {
                    moveElem.style.cursor = 'move';
                    let isDragging = false;
                    let startX, startY, initialX, initialY;

                    moveElem.onmousedown = (e) => {
                        isDragging = true;
                        startX = e.clientX;
                        startY = e.clientY;
                        initialX = mainElem.offsetLeft;
                        initialY = mainElem.offsetTop;
                        
                        // 防止文本被选中
                        e.preventDefault();
                    };

                    document.onmousemove = (e) => {
                        if (!isDragging) return;

                        const dx = e.clientX - startX;
                        const dy = e.clientY - startY;

                        mainElem.style.left = initialX + dx + 'px';
                        mainElem.style.top = initialY + dy + 'px';
                        mainElem.style.transform = 'none';  // 移除默认的居中定位
                    };

                    document.onmouseup = () => {
                        isDragging = false;
                    };
                }
            }

            // 添加最大化/最小化功能
            if (config.maxmin) {
                const mainElem = elem.querySelector('.fast-layer-main');
                const maxBtn = elem.querySelector('.fast-layer-max');
                const minBtn = elem.querySelector('.fast-layer-min');
                let isMaximized = false;
                let originalStyles = null;

                if (maxBtn) {
                    maxBtn.onclick = () => {
                        if (!isMaximized) {
                            // 保存原始样式
                            originalStyles = {
                                width: mainElem.style.width,
                                height: mainElem.style.height,
                                top: mainElem.style.top,
                                left: mainElem.style.left,
                                transform: mainElem.style.transform
                            };

                            // 最大化
                            Object.assign(mainElem.style, {
                                width: '100%',
                                height: '100%',
                                top: '0',
                                left: '0',
                                transform: 'none'
                            });
                            maxBtn.classList.add('fast-layer-maxed');
                        } else {
                            // 还原
                            Object.assign(mainElem.style, originalStyles);
                            maxBtn.classList.remove('fast-layer-maxed');
                        }
                        isMaximized = !isMaximized;
                    };
                }

                if (minBtn) {
                    minBtn.onclick = () => {
                        mainElem.classList.toggle('fast-layer-min');
                    };
                }
            }

            // 添加大小调整功能
            if (config.resize) {
                const mainElem = elem.querySelector('.fast-layer-main');
                const resizeHandle = elem.querySelector('.fast-layer-resize');
                let isResizing = false;
                let startX, startY, startWidth, startHeight;

                if (resizeHandle) {
                    resizeHandle.onmousedown = (e) => {
                        if (mainElem.dataset.resize !== 'true') return;  // 检查是否启用了大小调整
                        isResizing = true;
                        startX = e.clientX;
                        startY = e.clientY;
                        startWidth = mainElem.offsetWidth;
                        startHeight = mainElem.offsetHeight;
                        
                        document.body.style.cursor = 'se-resize';
                        e.preventDefault();
                    };

                    document.onmousemove = (e) => {
                        if (!isResizing) return;

                        const width = startWidth + (e.clientX - startX);
                        const height = startHeight + (e.clientY - startY);

                        mainElem.style.width = `${width}px`;
                        mainElem.style.height = `${height}px`;
                    };

                    document.onmouseup = () => {
                        if (isResizing) {
                            isResizing = false;
                            document.body.style.cursor = '';
                        }
                    };
                }
            }
        }

        _anim(elem, type) {
            const animations = {
                0: 'fade',    // 淡入
                1: 'zoom',    // 缩放
                2: 'slide',   // 滑动
                3: 'flip',    // 翻转
                4: 'bounce',  // 弹跳
                5: 'rotate'   // 旋转
            };

            if (type in animations) {
                elem.classList.add(`fast-anim-${animations[type]}`);
            }
        }

        // 添加获取图标HTML的私有方法
        _getIconHtml(icon) {
            const icons = {
                0: 'info',
                1: 'success',
                2: 'error',
                3: 'question',
                4: 'lock',
                5: 'sad',
                6: 'smile'
            };
            
            return `<i class="fast-icon fast-icon-${icons[icon] || 'info'}"></i>`;
        }

        // 在 Fast 类中添加 RTL 检测方法
        _isRTL() {
            return document.documentElement.dir === 'rtl';
        }
    }

    // 添加表单类
    class FastForm {
        constructor() {
            this._initialized = false;
            this._submitCallback = null;
            this._isSubmitting = false;
            this._callbacks = new Map();  // 存储不同表单的回调函数
            this.init();
        }

        init() {
            if (this._initialized) return;

            // 使用点击事件处理表单提交
            document.addEventListener('click', (e) => {
                const submitBtn = e.target;
                if (submitBtn.hasAttribute('fast-submit')) {
                    e.preventDefault();
                    const form = submitBtn.closest('form');
                    if (form && !this._isSubmitting) {
                        this._isSubmitting = true;
                        submitBtn.disabled = true;
                        
                        const filter = submitBtn.getAttribute('fast-submit');
                        this.validate(form, filter);
                        
                        setTimeout(() => {
                            this._isSubmitting = false;
                            submitBtn.disabled = false;
                        }, 500);
                    }
                }
            });

            // 监听输入框变化
            document.addEventListener('input', (e) => {
                const elem = e.target;
                if (elem.hasAttribute('fast-verify')) {
                    // 标记输入框已经有过输入
                    elem.dataset.hadInput = 'true';
                    this.validateElement(elem, false);
                }
            });

            // 监听失去焦点事件
            document.addEventListener('blur', (e) => {
                const elem = e.target;
                if (elem.hasAttribute('fast-verify')) {
                    // 只有当有值或已经输入过时才显示错误
                    const showMessage = elem.value.trim() || elem.dataset.hadInput;
                    this.validateElement(elem, showMessage);
                }
            }, true);

            this._initialized = true;
        }

        // 验证单个元素
        validateElement(elem, showMessage = false) {
            const rules = elem.getAttribute('fast-verify').split('|');
            const value = elem.value.trim();
            let isValid = true;
            let errorMessage = '';

            // 如果是必填项且为空，只在有过输入后才显示错误
            if (rules.includes('required') && !value) {
                if (elem.dataset.hadInput) {  // 添加标记，判断是否有过输入
                    isValid = false;
                    errorMessage = '此项不能为空';
                }
            } else {
                // 有值时才验证其他规则
                for (let rule of rules) {
                    if (rule !== 'required' && !this.checkRule(rule, value, elem)) {
                        isValid = false;
                        errorMessage = this.getErrorMessage(rule, value, elem);
                        break;
                    }
                }
            }

            if (!isValid) {
                elem.classList.add('fast-error');
                // 只在需要时显示消息，且不是密码确认错误时
                if (showMessage && !errorMessage.includes('密码不一致')) {
                    fast.msg(errorMessage, {
                        icon: 2,
                        shake: true,
                        time: 2000
                    });
                }
            } else {
                elem.classList.remove('fast-error');
            }

            return isValid;
        }

        // 验证表单
        validate(form, filter) {
            let isValid = true;
            let firstInvalidElem = null;
            const formData = {};
            let hasPasswordError = false;

            const elements = form.querySelectorAll('[fast-verify]');

            for (let elem of elements) {
                // 提交时标记所有必填项为已输入
                if (elem.getAttribute('fast-verify').includes('required')) {
                    elem.dataset.hadInput = 'true';
                }

                const value = elem.value.trim();
                formData[elem.name] = value;

                if (!this.validateElement(elem, true) && !firstInvalidElem) {
                    firstInvalidElem = elem;
                    isValid = false;
                    // 检查是否是密码确认错误
                    const rules = elem.getAttribute('fast-verify').split('|');
                    if (rules.some(rule => rule.startsWith('confirm:'))) {
                        hasPasswordError = true;
                    }
                }
            }

            if (!isValid) {
                if (hasPasswordError) {
                    fast.msg('两次输入的密码不一致', {
                        icon: 2,
                        shake: true,
                        time: 2000
                    });
                }
                firstInvalidElem.focus();
                return false;
            }

            this.trigger(`submit(${filter})`, {
                elem: form,
                field: formData
            });

            return true;
        }

        // 检查单个规则
        checkRule(rule, value, elem) {
            // 解析带参数的规则，如 min:6
            const [ruleName, param] = rule.split(':');

            switch (ruleName) {
                case 'required':
                    return value.length > 0;
                case 'email':
                    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
                case 'phone':
                    return /^1[3-9]\d{9}$/.test(value);
                case 'url':
                    return /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/.test(value);
                case 'number':
                    return /^-?\d*\.?\d+$/.test(value);
                case 'integer':
                    return /^-?\d+$/.test(value);
                case 'min':
                    return value.length >= parseInt(param);
                case 'max':
                    return value.length <= parseInt(param);
                case 'length':
                    const len = parseInt(param);
                    return value.length === len;
                case 'between':
                    const [min, max] = param.split(',').map(Number);
                    return value.length >= min && value.length <= max;
                case 'date':
                    return !isNaN(Date.parse(value));
                case 'idcard':
                    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
                case 'password':
                    // 至少包含一个大写字母、一个小写字母、一个数字，长度至少为8
                    return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(value);
                case 'chinese':
                    return /^[\u4e00-\u9fa5]+$/.test(value);
                case 'english':
                    return /^[a-zA-Z]+$/.test(value);
                case 'username':
                    // 4-16位字母、数字、下划线
                    return /^[a-zA-Z0-9_]{4,16}$/.test(value);
                case 'zip':
                    return /^\d{6}$/.test(value);
                case 'ip':
                    return /^(\d{1,3}\.){3}\d{1,3}$/.test(value);
                case 'confirm':
                    // 获取需要确认的密码框
                    const targetElem = document.querySelector(`[name="${param}"]`);
                    if (!targetElem) return false;
                    // 如果目标密码框为空，则不进行比较
                    if (!targetElem.value.trim()) return true;
                    // 比较两个密码是否一致
                    return value === targetElem.value.trim();
                default:
                    return true;
            }
        }

        // 添加错误提示信息
        getErrorMessage(rule, value, elem) {
            const [ruleName, param] = rule.split(':');
            
            // 如果是确认密码规则且验证失败
            if (ruleName === 'confirm') {
                const targetElem = document.querySelector(`[name="${param}"]`);
                if (!targetElem) return '未找到匹配的密码字段';
                if (!value) return '请输入确认密码';
                if (value !== targetElem.value.trim()) return '两次输入的密码不一致';
            }

            const messages = {
                required: '此项不能为空',
                email: '请输入正确的邮箱地址',
                phone: '请输入正确的手机号码',
                url: '请输入有效的网址',
                number: '请输入数字',
                integer: '请输入整数',
                min: `长度不能小于${param}个字符`,
                max: `长度不能超过${param}个字符`,
                length: `长度必须为${param}个字符`,
                between: `长度必须在${param}个字符之间`,
                date: '请输入有效的日期',
                idcard: '请输入有效的身份证号码',
                password: '密码必须包含大小写字母和数字，且不少于8位',
                chinese: '只能输入中文字符',
                english: '只能输入英文字母',
                username: '用户名必须为4-16位字母、数字或下划线',
                zip: '请输入有效的邮政编码',
                ip: '请输入有效的IP地址',
                confirm: '两次输入的密码不一致'
            };

            return messages[ruleName] || '输入格式不正确';
        }

        // 事件监听
        on(event, callback) {
            const match = event.match(/^submit\((.*?)\)$/);
            if (match) {
                const filter = match[1];
                this._callbacks.set(filter, callback);
            }
        }

        // 触发事件
        trigger(event, data) {
            const match = event.match(/^submit\((.*?)\)$/);
            if (match) {
                const filter = match[1];
                const callback = this._callbacks.get(filter);
                if (callback) {
                    callback(data);
                }
            }
        }
    }

    // 创建全局实例
    window.fast = new Fast();
})(window);
